package com.eric.husky.controller;

import com.eric.husky.common.utils.RedisUtil;
import com.eric.husky.common.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.eric.husky.common.CommonController;
import com.eric.husky.common.web.ResponseModel;
import com.eric.husky.bean.User;
import com.eric.husky.service.UserService;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

@RequestMapping(value = "/user")
@RestController
@Api(value="用户管理接口",tags={"User(用户管理)-增删改查;导入导出"})
public class UserController extends CommonController{

	@Autowired
	private UserService userService;
    @Autowired
	RedisUtil redisUtil;

	@ApiOperation(value = "获取分页数据" ,notes = "获取分页数据" )
    @GetMapping("/list")
    public Page<User> list(User user, Pageable page) {
        return userService.list(user, page);
    }

    @ApiOperation(value = "获取列表数据" ,notes = "获取列表数据" )
	@GetMapping("/findAll")
//    @RequiresRoles(value = {"admin"})
	public List<User> findAll(){
        User user = (User) SecurityUtils.getSubject().getPrincipal(); // 获取当前登录用户
        System.out.println("controllerh获得的东西"+user.getPhone());
	    return userService.findList();
	}

    @ApiOperation(value = "获取单条数据对象" ,notes = "获取单条数据对象")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query",name = "userid" ,value = "userID" , required = true, dataType = "Integer")
	})
	@GetMapping("/{userid}")
    public User get(@PathVariable Integer userid) {
		return userService.get(userid);
    }

    @ApiOperation(value = "保存单条数据", notes = "保存单条数据,id列为空则为新增,不为空则为修改")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "User",value = "user",required = false,dataType = "User")
    })
    @PostMapping("/save")
    public ResponseModel save(@RequestBody User user) {
        if(userService.findByPhone(user.getPhone())!=null){
            return ResponseModel.failure("该手机号已存在，请重新确认");
        }
        if(!StringUtils.isEmpty(user.getPassword())){
            user.setPassword((DigestUtils.md5DigestAsHex(user.getPassword().getBytes())));
        }
	    return ResponseModel.success(userService.save(user));
    }

    @ApiOperation(value = "注册新用户", notes = "注册新用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "User",value = "user",required = false,dataType = "User")
    })
    @PostMapping("/register")
    public ResponseModel register(@RequestBody User user,HttpServletResponse response) {
        return userService.register(user,response);
    }

    @ApiOperation(value = "删除用户管理", notes = "删除用户管理" )
    @ApiImplicitParams({ @ApiImplicitParam(name = "userids", value = "UserID", required = true, dataType = "String")
    })
    @RequestMapping(value = "/delete" ,method = { RequestMethod.DELETE})
    public ResponseModel delete(String userids) {
        try {
            String[] id_array = userids.split(",");
            for(String userid:id_array){
                userService.delete(Integer.parseInt(userid));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseModel.success("删除成功");
    }

    @ApiOperation(value = "登录" ,notes = "登录" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username" ,value = "用户名" , required = false, dataType = "String"),
            @ApiImplicitParam(name = "password" ,value = "密码" , required = false, dataType = "String")
    })
    @PostMapping("/login")
    public ResponseModel login(String username, String password, HttpServletResponse response){
        return userService.userLogin(username,password,response);
    }

    @ApiOperation(value = "更改密码" ,notes = "登录" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldpwd" ,value = "旧密码" , required = false, dataType = "String"),
            @ApiImplicitParam(name = "newpwd" ,value = "新密码" , required = false, dataType = "String")
    })
    @RequestMapping(value = "/updatePwd", method = { RequestMethod.POST  })
    public ResponseModel updatePwd(@RequestParam("oldpwd") String oldpwd, @RequestParam("newpwd") String newpwd, HttpSession session) {
        if (!StringUtils.isEmpty(oldpwd) && !StringUtils.isEmpty(newpwd)) {
            User user = (User)session.getAttribute("loginUser");
            if(user != null){
                String md5_password = DigestUtils.md5DigestAsHex(oldpwd.getBytes());
                String md5_passwordnew = DigestUtils.md5DigestAsHex(newpwd.getBytes());
                if(md5_password.equals(user.getPassword())){
                    userService.updatePwd(user.getUserid(),md5_passwordnew);
                    user.setPassword(md5_passwordnew);
                    session.setAttribute("loginUser",user);
                    return ResponseModel.success("更改成功",user);
                }else{
                    return ResponseModel.failure("用户密码错误");
                }
            }else{
                return ResponseModel.failure("用户不存在");
            }
        } else {
            // 登录失败，刷新本登录页
            return ResponseModel.failure("密码不能为空");
        }
    }
}